﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.ContentManagement;
using Orchard.Core.Contents.Controllers;
using Orchard.Core.Settings.Models;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Notify;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Users.Services;
using Orchard.Users.ViewModels;
using Orchard.Mvc.Extensions;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.Utility.Extensions;
using Orchard;
using Orchard.Themes;
using VIC.User.Models;
using VIC.User.ViewModels;
using Orchard.Mvc;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using Orchard.Core.Common.Models;
using Orchard.Media.Services;
using Orchard.Media.ViewModels;
using System.Web;
using System.Diagnostics.CodeAnalysis;
using Orchard.Media.Models;
using System.Net;
using System.Web.Hosting;


namespace VIC.User.Controllers
{
    [HandleError, Themed]
    public class AccountController : Controller
    {
        private readonly IMembershipService _membershipService;
        private readonly IAuthenticationService _authenticationService;
        private readonly IUserService _userService;
        private readonly IEnumerable<IUserEventHandler> _userEventHandlers;
        private readonly ISiteService _siteService;
        private readonly IOrchardServices _orchardServices;
        public readonly string DefaultAvatar, PublicAvatar;
        dynamic Shape { get; set; }

        public Localizer T { get; set; }
        //update
        private readonly IMediaService _mediaService;
        private readonly IContentManager _contentManager;
        //


        public AccountController(
           IAuthenticationService authenticationService,

           IOrchardServices orchardServices,
           IMembershipService membershipService,
           IUserService userService,
           IShapeFactory shapeFactory,
           IEnumerable<IUserEventHandler> userEventHandlers,
           ISiteService siteService,
            //update
            IMediaService mediaservices, IContentManager contentManager
            // 
            )
        {
            _authenticationService = authenticationService;
            _orchardServices = orchardServices;

            _membershipService = membershipService;
            _userService = userService;
            _userEventHandlers = userEventHandlers;
            _siteService = siteService;
            DefaultAvatar = "modules\\VIC.User\\Styles\\Images\\Avatar.jpg";
            PublicAvatar = "media\\default\\image\\";
            T = NullLocalizer.Instance;
            Shape = shapeFactory;
            //update
            _mediaService = mediaservices;
            _contentManager = contentManager;
            //
        }







        /*Hàm thay đổi tên file avata*/
        private string GenerateImageFileName(string sFilename)
        {

            string sAccount = _orchardServices.WorkContext.CurrentUser.UserName;
            return (sAccount) + "_" + sFilename;
        }
        /*Hàm thay đổi kích thước file hình*/
        public byte[] ResizeStream(Stream sFileStream)
        {

            int iMaxWidth = 172, iMaxHeight = 172;
            int iNewWidth, iNewHeight;
            var image = Image.FromStream(sFileStream);
            double dlWidthRatio = (double)image.Width / iMaxWidth;
            double dlHeightRatio = (double)image.Height / iMaxHeight;
            if (dlWidthRatio <= 1 && dlHeightRatio <= 1)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    sFileStream.Position = 0;
                    sFileStream.CopyTo(ms);
                    return ms.ToArray();
                }
            }
            else
            {
                if (dlWidthRatio > dlHeightRatio)
                {
                    iNewWidth = iMaxWidth;
                    iNewHeight = (int)(image.Height / dlWidthRatio);
                }
                else
                {
                    iNewHeight = iMaxHeight;
                    iNewWidth = (int)(image.Width / dlHeightRatio);
                }
            }

            var thumbnailBitmap = new Bitmap(iNewWidth, iNewHeight);

            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, iNewWidth, iNewHeight);
            thumbnailGraph.DrawImage(image, imageRectangle);
            using (MemoryStream memory = new MemoryStream())
            {
                thumbnailBitmap.Save(memory, image.RawFormat);
                thumbnailGraph.Dispose();
                thumbnailBitmap.Dispose();
                image.Dispose();
                return memory.ToArray();
            }
        }



        public ActionResult Index(UserIndexOptions options, PagerParameters pagerParameters)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list users")))
                return new HttpUnauthorizedResult();

            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

            // default options
            if (options == null)
                options = new UserIndexOptions();

            var vicers = _orchardServices.ContentManager
                .Query<VIC_UserPart, VIC_UserRecord>().List();
            

            var users = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>();
            foreach (var vicer in vicers)
            {
                var user = users.List().Where(u => u.Id == vicer.UserPart_Id).FirstOrDefault();
                vicer.User = user;
            }
            vicers = vicers.Where(v => v.User != null);
            switch (options.Filter)
            {
                case UsersFilter.Approved:
                    vicers = vicers.Where(v => v.User.RegistrationStatus == UserStatus.Approved);
                    break;
                case UsersFilter.Pending:
                    vicers = vicers.Where(v => v.User.RegistrationStatus == UserStatus.Pending);
                    break;
                case UsersFilter.EmailPending:
                    vicers = vicers.Where(v => v.User.EmailStatus == UserStatus.Pending);
                    break;
            }

            if (!String.IsNullOrWhiteSpace(options.Search))
            {
                vicers = vicers.Where(v => (v.FirstName + v.LastName).Contains(options.Search) || v.Email.Contains(options.Search));
            }

            var pagerShape = Shape.Pager(pager).TotalItemCount(vicers.Count());

            switch (options.Order)
            {
                case UsersOrder.Name:
                    vicers = vicers.OrderBy(v => (v.FirstName + v.LastName));
                    break;
                case UsersOrder.Email:
                    vicers = vicers.OrderBy(v => v.Email);
                    break;
            }

            var results = vicers.Skip(pager.GetStartIndex()).Take(pager.PageSize);
            //.Slice(pager.GetStartIndex(), pager.PageSize)
            //.ToList();

            var model = new VIC_UsersIndexViewModel
            {
                Users = results
                    .Select(x => new VIC_UserEntry { User = x })
                    .ToList(),
                Options = options,
                Pager = pagerShape
            };

            // maintain previous route data when generating page links
            var routeData = new RouteData();
            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
            routeData.Values.Add("Options.Order", options.Order);

            pagerShape.RouteData(routeData);

            return View(model);
        }


        [HttpPost]
        [FormValueRequired("submit.BulkEdit")]
        public ActionResult Index(FormCollection input)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage users")))
                return new HttpUnauthorizedResult();

            var viewModel = new UsersIndexViewModel { Users = new List<UserEntry>(), Options = new UserIndexOptions() };
            UpdateModel(viewModel);

            var checkedEntries = viewModel.Users.Where(c => c.IsChecked);
            switch (viewModel.Options.BulkAction)
            {
                case UsersBulkAction.None:
                    break;
                case UsersBulkAction.Approve:
                    foreach (var entry in checkedEntries)
                    {
                        Approve(entry.User.Id);
                    }
                    break;
                case UsersBulkAction.Disable:
                    foreach (var entry in checkedEntries)
                    {
                        Moderate(entry.User.Id);
                    }
                    break;
                case UsersBulkAction.ChallengeEmail:
                    foreach (var entry in checkedEntries)
                    {
                        SendChallengeEmail(entry.User.Id);
                    }
                    break;
            }

            return RedirectToAction("Index", ControllerContext.RouteData.Values);
        }

        [AlwaysAccessible]
        public ActionResult LogOn()
        {
            if (_authenticationService.GetAuthenticatedUser() != null)
                return Redirect("~/");
            return View();
        }

        [HttpPost]
        [AlwaysAccessible]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false)
        {
            var user = ValidateLogOn(userNameOrEmail, password);
            if (!ModelState.IsValid)
            {
                return View();
            }

            _authenticationService.SignIn(user, rememberMe);
            foreach (var userEventHandler in _userEventHandlers)
            {
                userEventHandler.LoggedIn(user);
            }

            return this.RedirectLocal(returnUrl);
        }

        public ActionResult LogOff(string returnUrl)
        {
            var wasLoggedInUser = _authenticationService.GetAuthenticatedUser();
            _authenticationService.SignOut();
            if (wasLoggedInUser != null)
                foreach (var userEventHandler in _userEventHandlers)
                {
                    userEventHandler.LoggedOut(wasLoggedInUser);
                }
            return this.RedirectLocal(returnUrl);
        }
        public ActionResult SendChallengeEmail(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage users")))
                return new HttpUnauthorizedResult();

            var user = _orchardServices.ContentManager.Get<IUser>(id);

            if (user != null)
            {
                var siteUrl = _orchardServices.WorkContext.CurrentSite.As<SiteSettings2Part>().BaseUrl;
                if (String.IsNullOrWhiteSpace(siteUrl))
                {
                    siteUrl = HttpContext.Request.ToRootUrlString();
                }

                _userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
                _orchardServices.Notifier.Information(T("Challenge email sent to {0}", user.UserName));
            }


            return RedirectToAction("Index");
        }

        public ActionResult Approve(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage users")))
                return new HttpUnauthorizedResult();

            var user = _orchardServices.ContentManager.Get<IUser>(id);

            if (user != null)
            {
                user.As<UserPart>().RegistrationStatus = UserStatus.Approved;
                _orchardServices.Notifier.Information(T("User {0} approved", user.UserName));
                foreach (var userEventHandler in _userEventHandlers)
                {
                    userEventHandler.Approved(user);
                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult Moderate(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage users")))
                return new HttpUnauthorizedResult();

            var user = _orchardServices.ContentManager.Get<IUser>(id);

            if (user != null)
            {
                if (String.Equals(_orchardServices.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal))
                {
                    _orchardServices.Notifier.Error(T("You can't disable your own account. Please log in with another account"));
                }
                else
                {
                    user.As<UserPart>().RegistrationStatus = UserStatus.Pending;
                    _orchardServices.Notifier.Information(T("User {0} disabled", user.UserName));
                }
            }

            return RedirectToAction("Index");
        }

        int MinPasswordLength
        {
            get
            {
                return _membershipService.GetSettings().MinRequiredPasswordLength;
            }
        }

     
        [AlwaysAccessible]
        public ActionResult Register()
        {
            // ensure users can register
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
            if (!registrationSettings.UsersCanRegister)
            {
                return HttpNotFound();
            }

            ViewData["PasswordLength"] = MinPasswordLength;

            var shape = _orchardServices.New.Register();
            //return new ShapeResult(this, shape);
            return View();
        }

        [HttpPost]
        [AlwaysAccessible]
        public ActionResult Register(VIC_UserNewVM model)
        {
            if (ModelState.IsValid == true)
            {

                // ensure users can register
                var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
                if (!registrationSettings.UsersCanRegister)
                {
                    return HttpNotFound();
                }

                ViewData["PasswordLength"] = MinPasswordLength;

                if (ValidateRegistration(model.FirstName, model.LastName, model.Email, model.Password, model.ConfirmPassword))
                {

                    // Attempt to register the user
                    // No need to report this to IUserEventHandler because _membershipService does that for us
                    var user = _membershipService.CreateUser(new CreateUserParams(model.Email, model.Password, model.Email, null, null, true));

                    if (user != null)
                    {
                        if (user.As<UserPart>().EmailStatus == UserStatus.Pending)
                        {
                            var siteUrl = _orchardServices.WorkContext.CurrentSite.As<SiteSettings2Part>().BaseUrl;
                            if (String.IsNullOrWhiteSpace(siteUrl))
                            {
                                siteUrl = HttpContext.Request.ToRootUrlString();
                            }

                            _userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));

                            foreach (var userEventHandler in _userEventHandlers)
                            {
                                userEventHandler.SentChallengeEmail(user);
                            }
                            return RedirectToAction("ChallengeEmailSent");
                        }

                        if (user.As<UserPart>().RegistrationStatus == UserStatus.Pending)
                        {
                            return RedirectToAction("RegistrationPending");
                        }
                        //Creating VIC.UserPart
                        var vicer = _orchardServices.ContentManager.New("VIC_User");
                        var part = vicer.As<VIC_UserPart>();
                        part.Email = model.Email;
                        part.FirstName = model.FirstName;
                        part.LastName = model.LastName;
                        part.UserPart_Id = user.Id;
                        part.ContentItem.As<CommonPart>().Owner = user;

                        _orchardServices.ContentManager.Create(vicer);

                        _authenticationService.SignIn(user, false /* createPersistentCookie */);


                        string file = Path.Combine(HostingEnvironment.ApplicationPhysicalPath + @DefaultAvatar);
                        string destination = Path.Combine(HostingEnvironment.ApplicationPhysicalPath + @PublicAvatar);


                        System.IO.File.Copy(file, destination + GenerateImageFileName("Avatar.jpg"));



                        part.Avatar = GenerateImageFileName("Avatar.jpg");
                        //chen hinh mac dinh

                        //
                        return Redirect("~/");
                    }

                    // ModelState.AddModelError("_FORM", T(ErrorCodeToString(/*createStatus*/MembershipCreateStatus.ProviderError)));
                }

                // If we got this far, something failed, redisplay form
                var shape = _orchardServices.New.Register();
                return new ShapeResult(this, shape);
            }
            else
            {
                return Register();
            }
        }
        #region Validation Methods
        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            //if (String.IsNullOrEmpty(currentPassword))
            //{
            //    ModelState.AddModelError("currentPassword", T("You must specify a current password."));
            //}
            //if (newPassword == null || newPassword.Length < MinPasswordLength)
            //{
            //    ModelState.AddModelError("newPassword", T("You must specify a new password of {0} or more characters.", MinPasswordLength));
            //}

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", T("Mật khẩu mới và xác nhận mật khẩu không khớp."));
            }

            return ModelState.IsValid;
        }
        private bool ValidateRegistration(string FirstName, string LastName, string email, string password, string confirmPassword)
        {
            bool validate = true;

            if (String.IsNullOrEmpty(FirstName))
            {
                ModelState.AddModelError("FirstName", T("You must specify a username."));
                validate = false;
            }
            if (String.IsNullOrEmpty(LastName))
            {
                ModelState.AddModelError("LastName", T("You must specify a username."));
                validate = false;
            }

            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", T("You must specify an email address."));
                validate = false;
            }
            else if (!Regex.IsMatch(email, UserPart.EmailPattern, RegexOptions.IgnoreCase))
            {
                // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx    
                ModelState.AddModelError("email", T("You must specify a valid email address."));
                validate = false;
            }

            if (!validate)
                return false;

            if (!_userService.VerifyUserUnicity(FirstName + LastName, email))
            {
                ModelState.AddModelError("userExists", T("User with that username and/or email already exists."));
            }
            if (password == null || password.Length < MinPasswordLength)
            {
                ModelState.AddModelError("password", T("You must specify a password of {0} or more characters.", MinPasswordLength));
            }
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match."));
            }
            return ModelState.IsValid;
        }
        private IUser ValidateLogOn(string userNameOrEmail, string password)
        {
            bool validate = true;

            if (String.IsNullOrEmpty(userNameOrEmail))
            {
                ModelState.AddModelError("userNameOrEmail", T("You must specify a username or e-mail."));
                validate = false;
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", T("You must specify a password."));
                validate = false;
            }

            if (!validate)
                return null;

            var user = _membershipService.ValidateUser(userNameOrEmail, password);
            if (user == null)
            {
                ModelState.AddModelError("_FORM", T("The username or e-mail or password provided is incorrect."));
            }

            return user;
        }
        #endregion
        [AlwaysAccessible]
        public ActionResult ChangePassword(int id)
        {
            //Nếu chưa đăng nhập thì return LogOn
            if (_orchardServices.WorkContext.CurrentUser == null)
            {
                return RedirectToAction("LogOn", "Account", new { Area = "VIC.User", ReturnUrl = Request.RawUrl });
            }
            ViewData["PasswordLength"] = MinPasswordLength;
            var vic_user = _contentManager.Get(id);
            VIC_UserChangePasswordVM model = new VIC_UserChangePasswordVM();
            model.Avatar = vic_user.As<VIC_UserPart>().Avatar;
            model.ID = id;
            return View(model);
        }
        [Authorize]
        [HttpPost]
        [AlwaysAccessible]
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Exceptions result in password not being changed.")]
        public ActionResult ChangePassword(VIC_UserChangePasswordVM model, int id)
        {
            ViewData["PasswordLength"] = MinPasswordLength;

            if (!ValidateChangePassword(model.Password, model.NewPassword, model.ConfirmPassword))
            {
                return ChangePassword(id);
            }

            try
            {
                var validated = _membershipService.ValidateUser(User.Identity.Name, model.Password);

                if (validated != null)
                {
                    _membershipService.SetPassword(validated, model.NewPassword);
                    foreach (var userEventHandler in _userEventHandlers)
                    {
                        userEventHandler.ChangedPassword(validated);
                    }
                    return RedirectToAction("ChangePasswordSuccess");
                }

                ModelState.AddModelError("_FORM",
                                         T("Mật khẩu hiện tại không đúng hoặc mật khẩu mới không hợp lệ."));
                return ChangePassword(id);
            }
            catch
            {
                ModelState.AddModelError("_FORM", T("Mật khẩu hiện tại không đúng hoặc mật khẩu mới không hợp lệ."));
                return ChangePassword(id);
            }
        }
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult ViewUser(int id)
        {
            var vic_user = _contentManager.Get(id);
            string sFirstName = vic_user.As<VIC_UserPart>().FirstName;
            string sLastName = vic_user.As<VIC_UserPart>().LastName;
            string sGender = vic_user.As<VIC_UserPart>().Gender;
            DateTime? sDateOfBirth = vic_user.As<VIC_UserPart>().DateOfBirth;
            string sEmail = vic_user.As<VIC_UserPart>().Email;
            string sAdress = vic_user.As<VIC_UserPart>().Address;
            string sPhoneNumber = vic_user.As<VIC_UserPart>().Phonenumber;
            string sSummaryCare = vic_user.As<VIC_UserPart>().SummaryCare;
            string sSummarySelf = vic_user.As<VIC_UserPart>().SummarySelf;
            string sWebsite = vic_user.As<VIC_UserPart>().Website;
            int UserRecordID = vic_user.As<VIC_UserPart>().UserPart_Id;
            string sSSN = vic_user.As<VIC_UserPart>().SSN;
            string sAvatar = vic_user.As<VIC_UserPart>().Avatar;

            VIC_UserEditVM model = new VIC_UserEditVM();

            model.IdUser = vic_user.Id;
            model.FirstName = sFirstName;
            model.LastName = sLastName;
            model.Gender = sGender;
            model.DateOfBirth = sDateOfBirth;
            model.Email = sEmail;
            model.Address = sAdress;
            model.Phonenumber = sPhoneNumber;
            model.SummaryCare = sSummaryCare;
            model.SummarySelf = sSummarySelf;
            model.Website = sWebsite;
            model.SSN = sSSN;
            model.Avatar = _mediaService.GetMediaPublicUrl("image", sAvatar);

            return View(model);
        }
        //Chinh sua thong tin nguoi dung
        public ActionResult EditUser(int id)
        {
            //Nếu chưa đăng nhập thì return LogOn
            if (_orchardServices.WorkContext.CurrentUser == null)
            {
                return RedirectToAction("LogOn", "Account", new { Area = "VIC.User", ReturnUrl = Request.RawUrl });
            }
            var vic_user = _contentManager.Get(id);
            //var vic_user = _orchardServices.ContentManager.New("VIC_User");
            if (!(vic_user.As<VIC_UserPart>().UserPart_Id == _orchardServices.WorkContext.CurrentUser.Id))
                return new HttpUnauthorizedResult();
            VIC_UserPart part = new VIC_UserPart();

            string sFirstName = vic_user.As<VIC_UserPart>().FirstName;
            string sLastName = vic_user.As<VIC_UserPart>().LastName;
            string sGender = vic_user.As<VIC_UserPart>().Gender;
            DateTime? sDateOfBirth = vic_user.As<VIC_UserPart>().DateOfBirth;
            string sEmail = vic_user.As<VIC_UserPart>().Email;
            string sAdress = vic_user.As<VIC_UserPart>().Address;
            string sPhoneNumber = vic_user.As<VIC_UserPart>().Phonenumber;
            string sSummaryCare = vic_user.As<VIC_UserPart>().SummaryCare;
            string sSummarySelf = vic_user.As<VIC_UserPart>().SummarySelf;
            string sWebsite = vic_user.As<VIC_UserPart>().Website;
            string sSSN = vic_user.As<VIC_UserPart>().SSN;
            int UserRecordID = vic_user.As<VIC_UserPart>().UserPart_Id;
            string sAvatar = vic_user.As<VIC_UserPart>().Avatar;

            VIC_UserEditVM model = new VIC_UserEditVM();
            //model.UserID = id;
            model.FolderName = "image";
            model.MediaPath = "image";
            model.Avatar = _mediaService.GetMediaPublicUrl("image", sAvatar);
            model.FirstName = sFirstName;
            model.LastName = sLastName;
            model.Gender = sGender;
            model.DateOfBirth = sDateOfBirth;
            model.Email = sEmail;
            model.SSN = sSSN;
            model.Address = sAdress;
            model.Phonenumber = sPhoneNumber;
            model.SummaryCare = sSummaryCare;
            model.SummarySelf = sSummarySelf;
            model.Website = sWebsite;

            //
            //model.Avata = _mediaService.GetMediaPublicUrl("image", vic_user.As<VIC_UserPart>().Avata);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false), ActionName("EditUser")]
        [FormValueRequired("submit.LuuThayDoi")]
        public ActionResult EditUser(VIC_UserEditVM model, int id)
        {
            if (ModelState.IsValid)
            {
                ///Dateofbirth
                
                string sDayOfBirth = "" + model.DayOfBirth;
                if (sDayOfBirth.Length == 1)
                    sDayOfBirth = "0" + sDayOfBirth;
                string sMonthOfBirth = model.MonthOfBirth.ToString();
                if (sMonthOfBirth.Length == 1)
                    sMonthOfBirth = "0" + sMonthOfBirth;
                string sYearOfBirth = model.YearOfBirth.ToString();
                IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
                DateTime sBirthDate = DateTime.ParseExact(sDayOfBirth + "-" + sMonthOfBirth + "-" + sYearOfBirth, "dd-MM-yyyy", theCultureInfo);

                var vic_user = _contentManager.Get(id);
                vic_user.As<VIC_UserPart>().FirstName = model.FirstName;
                vic_user.As<VIC_UserPart>().LastName = model.LastName;
                vic_user.As<VIC_UserPart>().Gender = model.Gender;
                vic_user.As<VIC_UserPart>().DateOfBirth = sBirthDate;
                vic_user.As<VIC_UserPart>().Email = model.Email;
                vic_user.As<VIC_UserPart>().Address = model.Address;
                vic_user.As<VIC_UserPart>().Phonenumber = model.Phonenumber;
                vic_user.As<VIC_UserPart>().SummaryCare = model.SummaryCare;
                vic_user.As<VIC_UserPart>().SummarySelf = model.SummarySelf;
                vic_user.As<VIC_UserPart>().SSN = model.SSN;
                vic_user.As<VIC_UserPart>().Website = model.Website;
                

                _orchardServices.Notifier.Information(T("User's information saved"));
                return EditUser(id);
            }
            else
            {
                return EditUser(id);
            }
        }

        /*Upload avatar*/
        [HttpPost, ValidateInput(false), ActionName("EditUser")]
        [FormValueRequired("submit.Upload")]
        public ActionResult UploadAvatar(VIC_UserEditVM model,int id)
        {
                var vic_user = _contentManager.Get(id);
                string sFilename = "";
                string sNewfilename = "";
                if (!String.IsNullOrWhiteSpace(Request.Files[0].FileName))
                {
                    sFilename = Request.Files[0].FileName;
                    sNewfilename = GenerateImageFileName(sFilename);
                    try
                    {
                        byte[] abData = ResizeStream((Request.Files[0] as HttpPostedFileBase).InputStream);
                        _mediaService.UploadMediaFile(model.MediaPath, sNewfilename, abData, false);
                        //_mediaService.UploadMediaFile(model.MediaPath, Request.Files[fileName], model.ExtractZip);


                        _mediaService.DeleteFile(model.MediaPath, vic_user.As<VIC_UserPart>().Avatar);

                        vic_user.As<VIC_UserPart>().Avatar = sNewfilename;
                    }
                    catch (ArgumentException e)
                    {
                        _orchardServices.Notifier.Error(T("Uploading media file failed: {0}", e.Message));
                        return EditUser(id);
                    }
                }
            
            return Redirect(Request.UrlReferrer.ToString());
        }
    }
}
